from . import admin_blue
from info.utils.comment import user_login_data
from flask import g,redirect,url_for,render_template,request,current_app,session
from info.models import User


@admin_blue.route('/user_count')
def user_count():
    '''用户量统计'''

    return render_template('admin/user_count.html')


@admin_blue.route('/')
@user_login_data
def admin_index():
    '''主页'''

    #获取登陆信息
    user = g.user
    if not user:
        return redirect(url_for('admin.admin_login'))

    context = {
        'user': user.to_dict()
    }

    return render_template('admin/index.html',context=context)


@admin_blue.route('/login', methods=['GET','POST'])
def admin_login():
    '''登陆'''

    # 提供登录界面
    if request.method == 'GET':

        # 检查用户是否已经登录，如果已经登录就进入到主页
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect(url_for('admin.admin_index'))

        return render_template('admin/login.html')

    #提供登陆页面
    if request.method == 'POST':
        #接受参数
        username = request.form.get('username')
        password = request.form.get('password')

        #校验参数
        if not all([username,password]):
            return render_template('admin/login.html',errmsg='缺少参数')

        # 查询要登陆的用户是否存在

        try:
            user = User.query.filter(User.nick_name == username).first()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/login.html',errmsg='查询用户数据失败')
        if not user:
            return render_template('admin/login.html',errmsg='用户名或者密码错误')

        #校验要登录的用户密码是否正确
        if not user.check_password(password):
            return render_template('admin/login.html',errmsg='用户名或者密码错误')

        #写入状态保持信息到session
        session['user_id'] = user.id
        session['nick_name'] = user.nick_name
        session['mobile'] = user.mobile
        session['is_admin'] = user.is_admin

        #响应登陆结果
        return redirect(url_for('admin.admin_index'))